<?php
namespace app\common\model\merchant;

use app\common\model\BaseModel;

/**
 * 商户API密钥模型
 * 管理商户的API密钥、权限和配额
 */
class MerchantApiKeyModel extends BaseModel
{
    public static function tableName(): string { return 'gf_api_keys'; }

    public static function tablePk(): ?string
    {
        return 'id';
    }

    /**
     * 获取关联的商户
     */
    public function getMerchant()
    {
        return $this->belongsTo(MerchantModel::class, 'merchant_id', 'id');
    }

    /**
     * 检查API密钥是否有效
     */
    public function isValid()
    {
        return $this->status === 'active' && 
               strtotime($this->expires_at) > time() &&
               $this->getMerchant()->isActive();
    }

    /**
     * 检查配额是否充足
     */
    public function hasQuota($requests = 1)
    {
        return ($this->daily_requests_used + $requests) <= $this->daily_requests_limit;
    }

    /**
     * 增加使用次数
     */
    public function incrementUsage($requests = 1)
    {
        $this->daily_requests_used += $requests;
        $this->total_requests_used += $requests;
        $this->last_used_at = date('Y-m-d H:i:s');
        $this->save();
    }
}